package com.zhongdaima.netty.analysis.part0.netty.nio;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 欢迎关注公众号“种代码“，获取博主微信深入交流
 *
 * @author wangjianxin
 */
public class HelloNettyServer {
    public static void main(String[] args) throws InterruptedException {
        //相当于com.zhongdaima.netty.analysis.part0.jdk.nio.NioServerConnector中的线程
        EventLoopGroup boss = new NioEventLoopGroup(1);
        //相当于com.zhongdaima.netty.analysis.part0.jdk.nio.NioServerHandler中的线程
        EventLoopGroup worker = new NioEventLoopGroup(1);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                byte[] bytes = new byte[((ByteBuf) msg).readableBytes()];
                                ((ByteBuf) msg).readBytes(bytes);
                                String name = new String(bytes);
                                //打印客户端发来的数据
                                System.out.println(name);
                                ctx.writeAndFlush(Unpooled.wrappedBuffer(("hello, " + name).getBytes()));
                            }
                        });
                    }
                });
        //绑定到8000端口
        ChannelFuture future = serverBootstrap.bind(8000).sync();
        //等待channel关闭
        future.channel().closeFuture().syncUninterruptibly();
    }
}
